<template>
  <div>
    <div>
      <el-form
        :inline="true"
        :model="queryForm"
        class="operation-form"
        size="small"
        ref="SearchForm"
      >
        <el-form-item label="接口名称">
          <el-input
            v-model="queryForm.apiName"
            placeholder="请输入接口名称"
            clearable
            style="width:180px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadInterface()">搜索</el-button>
          <el-button
            type="success"
            @click="saveContact"
            size="small"
            style="margin-left:600px"
            >保 存
          </el-button>
          <el-button
            @click="backCase"
            type="primary"
            size="small"
            style="margin-left:30px"
            >返回列表
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-container>
      <el-main style="padding: 0; display: flex">
        <el-card style="padding: 5px; padding-right:10px; margin-right: 5px;">
          <!-- // 左侧分组 -->
          <el-tree
            :data="treeData"
            :props="defaultProps"
            ref="tree"
            accordion
            node-key="id"
            highlight-current
            @node-click="handleNodeClick"
          >
          </el-tree>
        </el-card>

        <!-- // 拖拽列表 -->
        <el-card style="width: 50%; padding:5px;">
          <draggable
            class="left-draggable"
            :list="tableData"
            :group="{ name: 'people', pull: 'clone', put: false }"
          >
            <div
              class="list-group-item"
              v-for="(element, index) in tableData"
              :key="index"
              style="cursor: pointer; margin-top: 5px; overflow: auto;"
            >
              <div
                class="edit__block"
                :class="`block_${element.method.toLowerCase()}`"
              >
                <span
                  class="block-method block_method_color"
                  :class="`block_${element.method.toLowerCase()}`"
                >
                  {{ element.method.toUpperCase() }}
                </span>

                <div class="edit__block--inner">
                  <span class="block-method block_url">{{ element.url }}</span>
                  <span class="block-summary-description">{{
                    element.name
                  }}</span>
                </div>
              </div>
            </div>
          </draggable>
          <br />
          <div style="text-align: left">
            <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="pagination.total"
              :page-size="pagination.pageSize"
              :current-page.sync="pagination.page"
              @current-change="loadInterface(pagination.page, groupId)"
            >
            </el-pagination>
          </div>
        </el-card>

        <el-card
          style="width: 50%; padding:5px; margin-left: 10px; height: 98%"
        >
          <draggable class="right-draggable" :list="tableData2" group="people">
            <div
              class="list-group-item"
              v-for="(element, index) in tableData2"
              :key="`${element.name}${index}`"
              style="cursor: pointer; margin-top: 5px; overflow: auto;"
            >
              <div
                class="edit__block"
                :class="`block_${element.method.toLowerCase()}`"
              >
                <span
                  class="block-method block_method_color"
                  :class="`block_${element.method.toLowerCase()}`"
                >
                  {{ element.method.toUpperCase() }}
                </span>

                <div class="edit__block--inner">
                  <span class="block-summary-description">{{
                    element.name
                  }}</span>
                </div>
                <div style="margin-left:30px;margin-right:50px">
                  <i
                    class="el-icon-delete delete"
                    style="color: red"
                    @click="deleteComponents(index, element)"
                  ></i>
                </div>
              </div>
            </div>
          </draggable>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import { queryGroup } from "@/api/group";
import { queryInterface } from "@/api/interface";
import { addConnect } from "@/api/case";
import { isEmpty, cloneDeep } from "lodash";

export default {
  name: "Contact",
  props: ["caseId", "contactList"],
  components: {
    draggable
  },
  data() {
    return {
      tableData: [],
      tableData2: [],

      treeData: [],
      groupForm: {
        name: "",
        project_id: parseInt(window.localStorage.getItem("projectId")),
        pid: 0
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      contactForm: {
        case_id: undefined,
        api_list: []
      },

      queryForm: {
        config: undefined,
        apiName: undefined,
        envVar: undefined,
        status: undefined,
        node: undefined
      },

      groupID: undefined,

      // 【分页属性】
      pagination: {
        total: 0,
        page: 1,
        pageSize: 10
      }
    };
  },
  computed: {},
  watch: {},
  created() {
    this.loadInterface();
    this.loadGroup();
    this.tableData2 = isEmpty(this.contactList)
      ? []
      : cloneDeep(this.contactList);
  },
  mounted() {},
  methods: {
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([]);
      } else {
        if (node.data.children === undefined) {
          return resolve([]);
        } else {
          return resolve(node.data.children);
        }
      }
    },

    // 加载用例分组数据
    loadGroup() {
      this.disable = true;
      queryGroup({
        project_id: parseInt(window.localStorage.getItem("projectId")),
        page_size: 30
      })
        .then(res => {
          const result = res.data.result;
          this.treeData = result;
          this.getListData();
        })
        .catch(err => {
          console.log("错误消息：" + err);
        });
    },

    // tree树结构点击节点回调事件
    handleNodeClick(data, node) {
      this.groupForm.id = data.id;
      this.groupForm.pid = data.pid;
      this.groupForm.name = data.label;

      if (data.id === 0) {
        this.groupId = undefined;
      } else {
        this.groupId = data.id;
      }

      this.loadInterface(1, this.groupId);
    },

    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.loadInterface();
    },

    loadInterface(page = 1, group_id = undefined) {
      this.loading = true;
      queryInterface({
        page: page,
        page_size: this.pagination.pageSize,
        project_id: parseInt(window.localStorage.getItem("projectId")),
        group_id: group_id
      })
        .then(res => {
          let resData = res.data;
          if (resData.code == 200) {
            const result = res.data.result;
            for (let i = 0; i < result.length; i++) {
              result[i].interface_id = result[i].id;
            }
            this.tableData = result;
            this.pagination.total = res.data.total;
          } else {
            this.$message.error("加载接口数据失败： " + res.data.msg);
          }
          this.loading = false;
        })
        .catch(err => {
          console.log("错误消息：" + err);
        });
    },

    backCase() {
      const changeContract = true;
      this.$emit("changeContract", changeContract);
    },

    deleteComponents(index, item) {
      this.tableData2.splice(index, 1);
    },

    saveContact() {
      this.contactForm.case_id = this.caseId;
      const caseStep = [];

      console.log(this.tableData2);
      for (let i = 0; i < this.tableData2.length; i++) {
        caseStep.push(this.tableData2[i].interface_id);
      }

      this.contactForm.api_list = caseStep;

      console.log(caseStep, 11111111);

      addConnect(this.contactForm)
        .then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: "关联成功",
              type: "success"
            });
          }
        })
        .catch(err => {
          this.$message.error("关联失败" + err);
          console.log(err);
        });
      const changeContract = true;
      this.$emit("changeContract", changeContract);
    },

    // 解析tree数据
    getListData() {
      let dataArray = [];
      this.treeData.forEach(function(data) {
        let pid = data.pid;
        if (pid == 0) {
          let objTemp = {
            id: data.id,
            label: data.name,
            pid: pid
          };
          dataArray.push(objTemp);
        }
      });
      this.data2treeDG(this.treeData, dataArray);
      dataArray.unshift({
        id: 0,
        label: "默认分组",
        pid: 0
      });
    },

    // 解析children数据
    data2treeDG(treeData, dataArray) {
      for (let j = 0; j < dataArray.length; j++) {
        let dataArrayIndex = dataArray[j];
        let childrenArray = [];
        let Id = dataArrayIndex.id;
        for (let i = 0; i < treeData.length; i++) {
          let data = treeData[i];
          let pid = data.pid;
          if (pid == Id) {
            //判断是否为儿子节点
            let objTemp = {
              id: data.id,
              label: data.name,
              pid: pid
            };
            childrenArray.push(objTemp);
          }
        }
        if (childrenArray.length > 0) {
          dataArrayIndex.children = childrenArray;
        }
        if (childrenArray.length > 0) {
          //有儿子节点则递归
          this.data2treeDG(treeData, childrenArray);
        }
      }
      this.treeData = dataArray;
      return dataArray;
    }
  }
};
</script>

<style lang="less">
.left-draggable {
  height: 500px;
}

.right-draggable {
  height: 540px;
  overflow-y: auto;
}

.border-footer {
  text-align: right;
  margin: 5px;
}

.edit__block {
  position: relative;
  border-radius: 4px;
  height: 40px;
  overflow: hidden;
  padding: 2px;
  display: flex;
  align-items: center;
  line-height: 1;
}

.edit__block--inner {
  padding: 5px 0 5px 10px;
}

.edit__block--inner .block-method {
  padding: 0;
  text-align: left;
  margin-bottom: 4px;
}

.block_post {
  border: 1px solid #49cc90;
  background-color: rgba(73, 204, 144, 0.1);
}

.block_method_post {
  background-color: #49cc90;
}

.block_put {
  border: 1px solid #fca130;
  background-color: rgba(252, 161, 48, 0.1);
}

.block_method_put {
  background-color: #fca130;
}

.block_get {
  border: 1px solid #61affe;
  background-color: rgba(97, 175, 254, 0.1);
}

.block_method_get {
  background-color: #61affe;
}

.block_delete {
  border: 1px solid #f93e3e;
  background-color: rgba(249, 62, 62, 0.1);
}

.block_method_delete {
  background-color: #f93e3e;
}

.block_patch {
  border: 1px solid #50e3c2;
  background-color: rgba(80, 227, 194, 0.1);
}

.block_method_patch {
  background-color: #50e3c2;
}

.block_head {
  border: 1px solid #e6a23c;
  background-color: rgba(230, 162, 60, 0.1);
}

.block_method_head {
  background-color: #e6a23c;
}

.block_options {
  border: 1px solid #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}

.block_method_options {
  background-color: #409eff;
}

.block_url {
  word-break: normal;
  width: auto;
  display: block;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: hidden;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  font-family: Open Sans, sans-serif;
  color: #3b4151;
}

.block_name {
  padding-left: 5px;
  word-break: normal;
  width: auto;
  display: block;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: hidden;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  font-family: Open Sans, sans-serif;
  color: #3b4151;
}

.block_method_color {
  cursor: pointer;
  color: #fff;
  background-color: #42b983;
}

.block-method {
  font-size: 14px;
  font-weight: 600;
  min-width: 80px;
  padding: 6px 15px;
  text-align: center;
  border-radius: 3px;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
  font-family: Titillium Web, sans-serif;
}

.block-summary-description {
  word-break: normal;
  width: auto;
  display: block;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: hidden;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  font-family: Open Sans, sans-serif;
  color: #3b4151;
}

h4 {
  display: block;
  -webkit-margin-before: 1.33em;
  -webkit-margin-after: 1.33em;
  -webkit-margin-start: 0px;
  -webkit-margin-end: 0px;
  font-weight: bold;
}
</style>
